package com.hefan.common.ons.bean;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hefan.common.ons.TopicRegistry;
import org.apache.commons.lang.StringUtils;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ninglijun@guolele.com
 * @description <p>
 * 调用ONSProducer.sendMsg的时候使用的参数</br>
 * </p>
 */
public class Message implements Serializable {

    private TopicRegistry topic;
    private String key;
    //tag字段已被占用,如果需要请使用字段:key
    private String tag;
    private String jsonBody;
    private Map<String, Object> msgBody = new HashMap<String, Object>();

    public Message put(String key, String value) {
        msgBody.put(key, value);
        return this;
    }

    public com.aliyun.openservices.ons.api.Message translateToOnsMessage(String topicName) {
        String body = "";
        if (msgBody != null && msgBody.size() > 0) {
            try {
                body = new ObjectMapper().writeValueAsString(msgBody);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (StringUtils.isNotBlank(jsonBody)) {
            body = jsonBody;
        }
        return new com.aliyun.openservices.ons.api.Message(topicName, tag, key, body.getBytes());
    }

    public TopicRegistry getTopic() {
        return topic;
    }

    public void setTopic(TopicRegistry topic) {
        this.topic = topic;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getTag() {
        return tag;
    }

    public void setTag(String tag) {
        this.tag = tag;
    }

    public String getJsonBody() {
        return jsonBody;
    }

    public void setJsonBody(String jsonBody) {
        this.jsonBody = jsonBody;
    }

    public Map<String, Object> getMsgBody() {
        return msgBody;
    }

    public void setMsgBody(Map<String, Object> msgBody) {
        this.msgBody = msgBody;
    }
}
